var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

var LoginSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  pwd: {
    type: String,
    required: true,
  },
  gender: {
    type: Boolean,
    required: true
  },
  mobile: {
    type: String,
    required: true
  }
})
var LoginModel = mongoose.model('LoginModel', LoginSchema);
// POST register
router.post('/', (req, res, next) => {
  var userName = req.body.name;
  var userMobile = req.body.mobile;

  var login = new LoginModel(req.body);

  // 注册查询用户名或者手机号是否已经注册
  LoginModel.findOne({$or: [{name: userName}, {mobile: userMobile}]}, (err, data) => {
    // 查找失败
    if (err) return next(err);
    // 查找成功
    if (data) {
      res.json({
        success: false,
        msg: '用户名或者手机号已注册'
      })
      return next();
    }
    login.save((err) => {
      // 保存失败
      if (err) return next(err);
      return res.json({
        success: true,
        msg: '注册成功'
      })
    })
  })
  
});

module.exports = router;